<template>
  <el-dialog destroy-on-close draggable title="Split" v-model="visible" width="600">
    <el-form ref="custForm" :model="formData" :rules="rules">
      <el-table stripe :data="formData.list" style="width: 100%" :border="true">
        <el-table-column prop="blNo" label="B/L NO." minWidth="220" />
        <el-table-column prop="totalUnits" label="NO.& KIND OF PKGS" minWidth="160">
          <template #default="scope">
            <el-form-item :prop="'list.' + scope.$index + '.totalUnits'" :rules="rules.totalUnits"
              style="margin-bottom: 0;">
              <el-input-number v-model="scope.row.totalUnits" :min="1" :max="originalData.totalUnits" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="Operation" width="90" fixed="right">
          <template #default="{ $index }">
            <el-button v-if="$index > 0" type="text" @click="onDelete($index)">Delete</el-button>
          </template>
        </el-table-column>
      </el-table>
    
      <div class="footer-add" >
        <el-button type="text" @click="onAdd(scope)">Add</el-button>
        <div >
          <PreViewImageUpload :url="uploadUrl" :id="originalData.id" type="0" :isTable="false" :accept="accept"
            :dataName="'id,type'" @onSuccess="uploadSuccess" />
          <span>Upload LOI</span>
        </div> 
      </div>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary" :loading="isLoading" @click="onSubmit">{{ $t("ship.button.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts" name="SplitModal">
  // @ts-nocheck
  import { ref, reactive, defineExpose, getCurrentInstance } from 'vue'
  import { ElMessage } from "element-plus";
  import service from "@/utils/request";
  import { ElNotification, ElMessageBox } from "element-plus";
  import PreViewImageUpload from '@/components/ImageUpload/PreViewImageUpload.vue'
  const proxy = getCurrentInstance()?.proxy
  const isLoading = ref(false)
  const visible = ref(false)
  const originalData = ref({})
  const formData = ref({ list: [] })
  const rules = reactive({
    totalUnits: [
      { required: true, message: 'Please input total units', trigger: 'blur' }
    ]
  })

  // A code码
  let charCode = 65;

  const getChar = () => {
    const char = String.fromCharCode(charCode)
    charCode++
    return char
  }

  const onInit = ({ blNo, ...rst }) => {
    charCode = 65;
    originalData.value = { blNo, ...rst }
    formData.value.list = [
      {
        blNo: originalData.value.blNo + getChar(),
        totalUnits: rst.totalUnits - 1
      },
      {
        blNo: originalData.value.blNo + getChar(),
        totalUnits: 1
      }
    ]
    visible.value = true
  }

  const onDelete = (index) => {
    formData.value.list.splice(index, 1)
  }

  const onAdd = () => {
    if (formData.value.list.length >= 10) {
      ElMessage.warning('Max 10 rows')
      return
    }
    const length = formData.value.list.length
    formData.value.list.push({
      blNo: originalData.value.blNo + getChar(),
      totalUnits: 1
    })
  }

  const uploadFile = async(event)=>{ 
    formData.file =  event.target.files[0] 
    setTimeout(() => URL.revokeObjectURL(formData.file), 0)  
  }

  const onSubmit = () => {
    ElMessageBox.confirm("Confirm to Split the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel"
    }).then(async () => {
      let totalUnits = 0
      formData.value.list.forEach((item) => {
        totalUnits += item.totalUnits
      })
      if (totalUnits > originalData.value.totalUnits) {
        ElMessage.warning(`Total units cannot exceed original total units ${originalData.value.totalUnits}`)
        return
      }
      if (totalUnits === originalData.value.totalUnits && formData.value.list.length === 1) {
        ElMessage.warning(`Total units cannot be equal to original total units ${originalData.value.totalUnits}`)
        return
      }
      if(formData.splitFileUrl == null || formData.splitFileUrl ==""){
        ElMessage.warning(`LOI file should upload!`)
        return
      }
      proxy.$refs["custForm"].validate(valid => {
        if (valid) {
          isLoading.value = true;
          const details = formData.value.list.map(item => {
            return {
              blNo: item.blNo,
              totalUnits: item.totalUnits
            }
          })
     
          service.post("/shipping/cargoManifest/split", { id: originalData.value.id, details, splitFileUrl: formData.splitFileUrl }).then(() => { 
            proxy.$emit("success");
            visible.value = false;
          }).finally(() => {
            isLoading.value = false;
          })
        }
      })
    })
  }
  // 上传凭证
  const accept = ref('.pdf');
  const uploadUrl = ref("/shipping/cargoManifest/uploadVoucher");
  const uploadSuccess = (data) => {
    formData.splitFileUrl = data.photos[0] 
  }
  defineExpose({ onInit })
</script>
<style scoped lang="scss">
  .footer-add {
    display: flex;
    line-height: 32px;
    justify-content: space-between;
    margin-top: 10px;
  }
</style>